﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SYSoft
{
    /// <summary>
    /// 获取系统当前操作用户
    /// </summary>
    public interface IOperateUser
    {
        ClaimsPrincipal Principal { get; }

        string GetUserInfoFromToken(string ClaimType);
    }

    public class OperateUser:IOperateUser
    {
        public OperateUser(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        private readonly IHttpContextAccessor _httpContextAccessor;

        //没有通过认证的，User会为空
        public ClaimsPrincipal Principal => _httpContextAccessor.HttpContext?.User;


        public string GetToken()
        {
            var token = _httpContextAccessor.HttpContext?.Request?.Headers["Authorization"].FirstOrDefault();
            if(token!=null)
            {
              return  token.ToString().Replace("Bearer ", "");
            }
            return "";
        }

        public string GetUserInfoFromToken(string ClaimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var token = "";

            token = GetToken();
            // token校验
            if (!string.IsNullOrEmpty(token) && jwtHandler.CanReadToken(token))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).FirstOrDefault();
            }

            return "";
        }

    }



}
